package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Business;
import cn.wolfcode.qo.BusinessQueryObject;
import cn.wolfcode.service.IBusinessService;
import cn.wolfcode.util.FileUploadUtil;
import cn.wolfcode.util.RequirePermission;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/business")
public class BusinessController {
    @Autowired
    private IBusinessService businessService;


    @RequestMapping("/list")
    @RequirePermission(name = "门店查询",expression = "business:list")
    public String list(Model model,@ModelAttribute("qo") BusinessQueryObject qo) {
        // 分页和过滤
        model.addAttribute("pageInfo", businessService.query(qo));
        return "business/list";
    }

    @RequestMapping("/delete")
    @RequirePermission(name = "门店删除",expression = "business:delete")
    public String delete(Long id) {
        if (id != null) {
            businessService.delete(id);
        }
        return "redirect:/business/list";
    }

    @RequestMapping("/input")
    @RequirePermission(name = "门店编辑",expression = "business:saveOrUpdate")
    public String input(Model model,Long id) {
        if (id != null) {
            model.addAttribute("business", businessService.get(id));
        }
        return "business/input";
    }

    @RequestMapping("/saveOrUpdate")
    @RequirePermission(name = "门店编辑",expression = "business:saveOrUpdate")
    public String saveOrUpdate(Business business, MultipartFile file) throws Exception {
        // 文件上传 营业执照上传
        if (file != null && file.getSize() > 0) {
           // 获取项目下的 static 目录的绝对路径，
            String realPath = UserContext.getRequest().getServletContext().getRealPath("/static");
            // 获得文件名加路径
            String filePath = FileUploadUtil.uploadFile(file, realPath);
            business.setLicenseImg("/static"+filePath);
        }
        if (business.getId() != null) {
            businessService.update(business);
        } else {
            businessService.insert(business);
        }
        return "redirect:/business/list";
    }

    // 门店详情
    @RequestMapping("/part")
    @ResponseBody
    public Business part(Business business) {
        if (business.getId() != null) {
            business = businessService.get(business.getId());
        }
        return business;
    }
}
